package com.epfresh.supplier.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.CustomDialog;
import com.epfresh.api.utils.JsonUtils;
import com.epfresh.supplier.R;
import com.epfresh.supplier.adapter.ClassifyViewBinder;
import com.epfresh.supplier.dialog.ClassifyEditDialog;
import com.epfresh.supplier.entity.ContentEntity;
import com.epfresh.supplier.entity.ProductClassify;
import com.epfresh.supplier.entity.StoreClassify;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import multitype.MultiTypeAdapter;
import multitype.OnRecyclerViewItemClickListener;

public class ProductClassifyManagerActivity extends BaseActivity {


    RecyclerView rv;
    MultiTypeAdapter mMultiAdapter;
    TextView tvBtn;
    ClassifyViewBinder classifyViewBinder;
    List<ProductClassify> mItems = new ArrayList<>();
    String topCategoryId;
    String storeCategoryId;
    //1,选择分类,2,二级分类
    int type = -1;
    boolean storeCategoryOnly;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (savedInstanceState != null) {
            getIntent().putExtra("type", savedInstanceState.getInt("type"));
            getIntent().putExtra("isCanEdit", savedInstanceState.getInt("isCanEdit"));
            getIntent().putExtra("categoryName", savedInstanceState.getString("categoryName"));
            getIntent().putExtra("categoryId", savedInstanceState.getString("categoryId"));
            getIntent().putExtra("topCategoryId", savedInstanceState.getString("topCategoryId"));
            getIntent().putExtra("storeCategoryId", savedInstanceState.getString("storeCategoryId"));
            getIntent().putExtra("storeCategoryOnly", savedInstanceState.getBoolean("storeCategoryOnly",false));
        }
        setContentView(R.layout.activity_classify_manager);

        type = getIntent().getIntExtra("type", -1);
        topCategoryId = getIntent().getStringExtra("topCategoryId");
        storeCategoryId = getIntent().getStringExtra("storeCategoryId");
        storeCategoryOnly = getIntent().getBooleanExtra("storeCategoryOnly",false);



        if (type == 2){
            toolbarTitle.setText("二级分类");
        }else if (type == 1){
            toolbarTitle.setText("选择分类");
        }else {
            toolbarTitle.setText("分类管理");
        }
        ivBack.setVisibility(View.VISIBLE);
        tvBack.setVisibility(View.VISIBLE);


        rv = (RecyclerView) findViewById(R.id.rv);
        tvBtn = (TextView) findViewById(R.id.tv_next);
        tvBtn.setOnClickListener(this);
        /*if (type == 1){
            rightbtn.setVisibility(View.GONE);
            tvBtn.setVisibility(View.GONE);
        }else {
            tvBtn.setVisibility(View.VISIBLE);
            rightbtn.setVisibility(View.VISIBLE);
        }*/
        tvBtn.setVisibility(View.VISIBLE);
        rightbtn.setVisibility(View.VISIBLE);

        if (BaseApplication.getInstance().isCategoryLevelOne() || type == 2){

            rightbtn.setText("编辑");
            rightbtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    edit();
                }
            });
        }else {
            findViewById(R.id.ll_btn).setVisibility(View.GONE);
            rightbtn.setText("编辑");
//            rightbtn.setText("管理");
            rightbtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    intoPlat();
                }
            });
        }
        rightbtn.setTextColor(0xff6f6f6f);
        LinearLayoutManager lm = new LinearLayoutManager(this);
        rv.setLayoutManager(lm);
        classifyViewBinder = new ClassifyViewBinder();
        if (type == 1) {
            classifyViewBinder.setShowSelect(true);
        }
        classifyViewBinder.setOnEditListener(new ClassifyViewBinder.OnEditListener() {
            @Override
            public void onEdit(int type, int position, ProductClassify pc) {
                if (type == 1){//编辑
                    editItem(position,pc);
                }else if (type == 2){//删除
                    deleteItem(position,pc);
                }
            }
        });

        classifyViewBinder.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object data) {
                if (position < mItems.size() &&data !=null && data instanceof ProductClassify){
                    onItem(position,(ProductClassify)data);
                }
            }
        });
        mMultiAdapter = new MultiTypeAdapter();

        mMultiAdapter.register(ProductClassify.class, classifyViewBinder);

        rv.setAdapter(mMultiAdapter);

        mMultiAdapter.setItems(mItems);


        loadInfo();


    }


    @Override
    protected void onRestart() {
        super.onRestart();
        loadInfo();
    }

    private void loadInfo() {
        if (topCategoryId != null && !"".equals(topCategoryId) && !BaseApplication.getInstance().isCategoryLevelOne()) {
            reqTopStoreCategory();
        }else {
            reqStoreCategory();

        }
    }

    private void intoPlat() {
        Intent intent = new Intent(this,ProductClassifyPlatActivity.class);

        startActivity(intent);

    }

    private void onItem(int position, ProductClassify data) {

        //发布商品选择
        if (type == 1){

            Intent intent = new Intent();
            intent.putExtra("storeCategoryName",data.getName());
            intent.putExtra("storeCategoryId",data.getId());
            intent.putExtra("isPlatType",data.isPlatType());
            setResult(RESULT_OK,intent);
            finish();
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt("type", type);
        outState.putString("categoryName", getIntent().getStringExtra("categoryName"));
        outState.putString("categoryId", getIntent().getStringExtra("categoryId"));
        outState.putString("topCategoryId", getIntent().getStringExtra("topCategoryId"));
        outState.putString("storeCategoryId", getIntent().getStringExtra("storeCategoryId"));
        outState.putBoolean("storeCategoryOnly", getIntent().getBooleanExtra("storeCategoryOnly",false));
        super.onSaveInstanceState(outState);

    }

    //删除
    private void deleteItem(int position, ProductClassify pc) {



        mPc = pc;


        CustomDialog.Builder builder = new CustomDialog.Builder(this);

        String s = "是否删除";

        builder.setTitleVisible(false).setMessage(s)//设置显示的内容
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                        dialog.dismiss();
                        reqDeleteStoreCategory(mPc.getId());
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//响应事件
                dialog.dismiss();
            }

        });//在按键响应事件中显示此对话框

        builder.create().show();



    }
    ProductClassify mPc;
    //编辑
    private void editItem(int position, ProductClassify pc) {
        if (dialog == null){
            dialog = new ClassifyEditDialog(this);
        }
        mPc = pc;
        dialog.setOnSureListener(onEditListener);
        dialog.show("编辑分类",pc.getName());
    }


    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.toolbar_title:
            case R.id.toolbar_title_flag:


                break;


            case R.id.tv_next:

                add();
                break;
        }
    }


    ClassifyEditDialog dialog;
    View.OnClickListener onAddListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String input = dialog.getInput();

            if (input == null ||"".equals(input)){
                toast("请输入商品分类名称");
                return;
            }
            dialog.dismiss();
            reqAddStoreCategory(input);


        }
    };
    View.OnClickListener onEditListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String input = dialog.getInput();
            if (input == null ||"".equals(input)){
                toast("请输入商品分类名称");
                return;
            }
            dialog.dismiss();


            if (mPc != null){
                reqModifyStoreCategory(mPc.getId(),input);
            }
        }
    };
    private void add() {

        if (dialog == null){
            dialog = new ClassifyEditDialog(this);
        }
        dialog.setOnSureListener(onAddListener);
        dialog.show("添加分类","");
    }

    private void edit() {

        String s = rightbtn.getText().toString();

        if ("编辑".equals(s)) {
            rightbtn.setText("取消");
            classifyViewBinder.setEdit(true);
            mMultiAdapter.notifyDataSetChanged();
        } else if ("取消".equals(s)) {
            rightbtn.setText("编辑");
            classifyViewBinder.setEdit(false);
            mMultiAdapter.notifyDataSetChanged();
        }


    }


    private void reqStoreCategory() {


        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_storeTopCategory_list);

       /* "storeId": "",
        "pageNumber": "1",
        "pageSize": "10"*/
        RequestEntityMapSupply.putParameter("storeId", BaseApplication.getInstance().getStoreId());
        RequestEntityMapSupply.putParameter("merchantId", BaseApplication.getInstance().getMerchantId());


        request(RequestEntityMapSupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_storeTopCategory_list, onStoreCategoryRequestListener);
    }

    private OnRequestListener<StoreClassify> onStoreCategoryRequestListener = new OnRequestListener<StoreClassify>() {
        @Override
        public StoreClassify jsonToObj(String responseStr) {
            //return JsonUtils.fromJsonObject(responseStr, ContentEntity.class, StoreClassify.class);
            return new Gson().fromJson(responseStr, StoreClassify.class);

        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<StoreClassify> response, Object tag) {
            mItems.clear();

            if (response != null) {
                StoreClassify result = response.getResponseElement();
                if (result != null) {
/*                    StoreClassify result = responseElement.getResult();
                    if (result != null) {*/
                        //一级分类
                        if (BaseApplication.getInstance().getMerchant().isCategoryLevelOne()) {

                            List<ProductClassify> storeTopCategories = result.getStoreTopCategories();
                            if (storeTopCategories != null && storeTopCategories.size() > 0) {
                                mItems.clear();

                                for (int i = 0; i < storeTopCategories.size(); i++) {
                                    ProductClassify productClassify = storeTopCategories.get(i);
                                    Log.e("storeCategoryId","storeCategoryId:"+productClassify.getId());

                                    if (storeCategoryId != null && !"".equals(storeCategoryId) && storeCategoryId.equals(productClassify.getId())) {
                                        productClassify.setSelect(true);
                                    } else {
                                        productClassify.setSelect(false);

                                    }
                                    mItems.add(productClassify);
                                }

                            }
                        } else {
                            //二级分类
                            List<ProductClassify> storeCategories = result.getStoreCategories();
                            if (storeCategories != null && storeCategories.size() > 0) {
                                mItems.clear();
                                String categoryId = getIntent().getStringExtra("categoryId");
                                String categoryName = getIntent().getStringExtra("categoryName");
                                if (categoryId != null && !"".equals(categoryId)){
                                    ProductClassify pc = new ProductClassify();

                                    pc.setPlatType(true);
                                    pc.setId(categoryId);
                                    pc.setName(categoryName);
                                    mItems.add(pc);
                                }

                                mItems.addAll(storeCategories);
                            }

                        //}
                    }
                }
                mMultiAdapter.notifyDataSetChanged();
            }

        }
    };
    private void reqModifyStoreCategory(String id ,String name) {


        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_storeTopCategory_modify);

       /* "storeId": "",
        "pageNumber": "1",
        "pageSize": "10"*/

        RequestEntityMapSupply.putParameter("storeId", BaseApplication.getInstance().getStoreId());
        RequestEntityMapSupply.putParameter("merchantId", BaseApplication.getInstance().getMerchantId());
        if(BaseApplication.getInstance().isCategoryLevelOne()){
            RequestEntityMapSupply.putParameter("storeTopCategoryId", id);
            RequestEntityMapSupply.putParameter("storeTopCategoryName", name);

       }else {
            RequestEntityMapSupply.putParameter("storeCategoryId", id);
            RequestEntityMapSupply.putParameter("storeCategoryName", name);

       }


        request(RequestEntityMapSupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_storeTopCategory_modify, onModifyStoreCategoryRequestListener);
    }

    private OnRequestListener<StatusEntity> onModifyStoreCategoryRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return JsonUtils.fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {

            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {

            hideProgressDialog();
            StatusEntity responseElement = response.getResponseElement();

            if (responseElement != null){
                if(responseElement.isSuccess()){
                    toast("修改成功");
                    loadInfo();
                }
            }


        }
    };
    private void reqDeleteStoreCategory(String id ) {


        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_storeTopCategory_delete);

       /* "storeId": "",
        "pageNumber": "1",
        "pageSize": "10"*/

        RequestEntityMapSupply.putParameter("storeId", BaseApplication.getInstance().getStoreId());
        RequestEntityMapSupply.putParameter("merchantId", BaseApplication.getInstance().getMerchantId());
        if(BaseApplication.getInstance().isCategoryLevelOne()){
            RequestEntityMapSupply.putParameter("storeTopCategoryId", id);

       }else {
            RequestEntityMapSupply.putParameter("storeCategoryId", id);
            RequestEntityMapSupply.putParameter("topCategoryId", topCategoryId);
       }


        request(RequestEntityMapSupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_storeTopCategory_delete, onDeleteStoreCategoryRequestListener);
    }

    private OnRequestListener<StatusEntity> onDeleteStoreCategoryRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return JsonUtils.fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {

            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {

            hideProgressDialog();
            StatusEntity responseElement = response.getResponseElement();

            if (responseElement != null){
                if(responseElement.isSuccess()){
                    toast("删除成功");
                    loadInfo();
                }
            }


        }
    };
    private void reqAddStoreCategory(String name ) {


        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_storeTopCategory_add);

       /* "storeId": "",
        "pageNumber": "1",
        "pageSize": "10"*/

        RequestEntityMapSupply.putParameter("storeId", BaseApplication.getInstance().getStoreId());
        RequestEntityMapSupply.putParameter("merchantId", BaseApplication.getInstance().getMerchantId());
        if(BaseApplication.getInstance().isCategoryLevelOne()){
            RequestEntityMapSupply.putParameter("storeTopCategoryName", name);

       }else {
            RequestEntityMapSupply.putParameter("storeCategoryName", name);
            RequestEntityMapSupply.putParameter("topCategoryId", topCategoryId);
       }


        request(RequestEntityMapSupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_storeTopCategory_add, onAddStoreCategoryRequestListener);
    }

    private OnRequestListener<StatusEntity> onAddStoreCategoryRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return JsonUtils.fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {

            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {
            hideProgressDialog();
            StatusEntity responseElement = response.getResponseElement();

            if (responseElement != null){
                if(responseElement.isSuccess()){
                    toast("添加成功");
                    loadInfo();
                }
            }


        }
    };




    private void reqTopStoreCategory() {


        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_storeTopCategory_topCategoryOrCategoryList);

       /* "storeId": "",
        "pageNumber": "1",
        "pageSize": "10"*/
        RequestEntityMapSupply.putParameter("storeId", BaseApplication.getInstance().getStoreId());
        RequestEntityMapSupply.putParameter("merchantId", BaseApplication.getInstance().getMerchantId());
        RequestEntityMapSupply.putParameter("storeCategoryOnly", storeCategoryOnly);
        RequestEntityMapSupply.putParameter("topCategoryId", topCategoryId);
        request(RequestEntityMapSupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_storeTopCategory_topCategoryOrCategoryList, onTopStoreCategoryRequestListener);
    }

    private OnRequestListener<StoreClassify> onTopStoreCategoryRequestListener = new OnRequestListener<StoreClassify>() {
        @Override
        public StoreClassify jsonToObj(String responseStr) {
            //return JsonUtils.fromJsonObject(responseStr, ContentEntity.class, StoreClassify.class);
            return new Gson().fromJson(responseStr, StoreClassify.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<StoreClassify> response, Object tag) {
            mItems.clear();

            if (response != null) {
                StoreClassify result = response.getResponseElement();
                if (result != null) {
/*                    StoreClassify result = responseElement.getResult();
                    if (result != null) {*/
                        List<ProductClassify> topCategories = result.getCategories();
                        //mItems.clear();
                        String categoryId = getIntent().getStringExtra("categoryId");
                        String categoryName = getIntent().getStringExtra("categoryName");

                        if (topCategories != null && topCategories.size() > 0) {
                            for (int i = 0; i < topCategories.size(); i++) {
                                ProductClassify productClassify = topCategories.get(i);
                               /* Log.e("storeCategoryId","storeCategoryId:"+productClassify.getId());

                                if (storeCategoryId != null && !"".equals(storeCategoryId) && storeCategoryId.equals(productClassify.getId())) {
                                    productClassify.setSelect(true);
                                } else {
                                    productClassify.setSelect(false);

                                }*/
                                mItems.add(productClassify);
                            }
//                            mMultiAdapter.notifyDataSetChanged();
                        }
                        if (categoryId != null && !"".equals(categoryId)){
                            ProductClassify pc = new ProductClassify();

                            pc.setPlatType(true);
                            pc.setId(categoryId);
                            pc.setName(categoryName);
                            mItems.add(pc);
                        }
                    }
            }
            mMultiAdapter.notifyDataSetChanged();
        }

      //  }
    };

}
